package edu.seu.mart.controller;

import edu.seu.mart.entity.Pager;
import edu.seu.mart.model.*;
import edu.seu.mart.service.ICommentService;
import edu.seu.mart.service.IGoodsService;
import edu.seu.mart.service.IHistoryService;
import edu.seu.mart.service.IOrderService;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * Created by zj on 2015/3/11.
 */
@Controller
@RequestMapping("/goods")
public class GoodsController {

    @Resource
    private IGoodsService goodsService;
    @Resource
    private ICommentService commentService;
    @Resource
    private IOrderService orderService;
    @Resource
    private IHistoryService historyService;

    private  int goodsId;
    private List reviewGoods =new ArrayList();
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(Model model) {
        List<Goods> list1 = goodsService.findGoodsByCategory("bjb").getDatas();
        List<Goods> list2 = goodsService.findGoodsByCategory("tsj").getDatas();
        List<Goods> list3 = goodsService.findGoodsByCategory("pb").getDatas();
        List<Goods> bjb = new ArrayList<>();
        List<Goods> tsj = new ArrayList<>();
        List<Goods> pb = new ArrayList<>();
        for (int i = 0; i < 3; i ++) {
            bjb.add(list1.get(i));
            tsj.add(list2.get(i));
            pb.add(list3.get(i));
        }
        model.addAttribute("bjb", bjb);
        model.addAttribute("tsj", tsj);
        model.addAttribute("pb", pb);
        return "goods/index";
    }

    @RequestMapping(value = "/{category}/search")
    public String findGoodsByChoice(Model model,@PathVariable String category,HttpServletRequest request, HttpSession session) {
        String price=request.getParameter("price");
        String brand=request.getParameter("brand");
        String CPU=request.getParameter("CPU");
        String SaleOrder=request.getParameter("SaleOrder");
        String priceOrder=request.getParameter("priceOrder");
        Pager<Goods> MatchedGoods=goodsService.findGoodsByCategory(category,brand,price,CPU,SaleOrder,priceOrder);
        List<List<Goods>>  goodsList = new ArrayList<List<Goods>>( ){};
        List<Goods>  smallGoodsList=new ArrayList<Goods>(){};
        if(MatchedGoods.getDatas().size()<3){
            for(int i=0;i<MatchedGoods.getDatas().size();i++)
            {
                smallGoodsList.add(MatchedGoods.getDatas().get(i));
            }
            goodsList.add(smallGoodsList);
        }else{
            for(int i=0;i<MatchedGoods.getDatas().size();i++)
            {
                if(i%3==0&&i!=0){
                    goodsList.add(smallGoodsList);
                    smallGoodsList=new ArrayList<Goods>(){};
                }
                smallGoodsList.add(MatchedGoods.getDatas().get(i));
            }
        }
        model.addAttribute("goodsList", goodsList);
        model.addAttribute("category", category);
        model.addAttribute("MatchedGoods", goodsService.findGoodsByCategory(category));

        User user = (User) session.getAttribute("loginUser");
        if (user != null) {
            List<History> list = historyService.findHistoryByUserId(user.getId());
            List<Goods> glist = new ArrayList<>();
            for (History history : list) {
                Goods goods = goodsService.load(history.getGoodsId());
                glist.add(goods);
            }
            model.addAttribute("historyList", glist);
        }

        return "goods/search";
    }
    @RequestMapping(value = "/findGoodsBySearch")
    public String findGoodsBySearch(Model model,@RequestParam String search,HttpServletRequest request) {
        File indexDir = new File(goodsService.getIndexDir());
        if (!indexDir.exists()) {
            goodsService.creatIndexDir();
        }
        List<Goods> GoodsList=goodsService.searchIndex(search);
        List<List<Goods>>  goodsList = new ArrayList<List<Goods>>( ){};
        List<Goods>  smallGoodsList=new ArrayList<Goods>(){};
        if(GoodsList.size()<3){

            goodsList.add(GoodsList);
        }else{
            for(int i=0;i<GoodsList.size();i++)
            {
                if(i%3==0&&i!=0){
                    goodsList.add(smallGoodsList);
                    smallGoodsList=new ArrayList<Goods>(){};
                }
                smallGoodsList.add(GoodsList.get(i));
            }
        }
        model.addAttribute("goodsList", goodsList);
        return "goods/search";
    }


    @RequestMapping(value = "/{search}/{category}/search")
    public String findMatchedGoods(@PathVariable String search, @PathVariable String category,Model model,HttpServletRequest request) {
        String SaleOrder=request.getParameter("SaleOrder");
        String priceOrder=request.getParameter("priceOrder");
        Pager<Goods> MatchedGoods=goodsService.findMatchedGoods(search, category,SaleOrder,priceOrder);
        List<List<Goods>>  goodsList = new ArrayList<List<Goods>>( ){};
        List<Goods>  smallGoodsList=new ArrayList<Goods>(){};
        if(MatchedGoods.getDatas().size()<3){
            for(int i=0;i<MatchedGoods.getDatas().size();i++)
            {
                smallGoodsList.add(MatchedGoods.getDatas().get(i));
            }
            goodsList.add(smallGoodsList);
        }else{
            for(int i=0;i<MatchedGoods.getDatas().size();i++)
            {
                if(i%3==0&&i!=0){
                    goodsList.add(smallGoodsList);
                    smallGoodsList=new ArrayList<Goods>(){};
                }
                smallGoodsList.add(MatchedGoods.getDatas().get(i));
            }
        }
        model.addAttribute("category", category);
        model.addAttribute("goodsList", goodsList);
        model.addAttribute("MatchedGoods", MatchedGoods);

        return "goods/search";
    }


    @RequestMapping(value = "/goodsDetail/{id}", method = RequestMethod.GET)
    public String goodsDetail(@PathVariable int id, Model model, HttpSession session) {
        /**
         * 添加用户浏览记录
         */
        User user = (User) session.getAttribute("loginUser");
        if (user != null) {
            int userId = user.getId();
            int hid = historyService.isBrowsed(userId, id);
            History history;
            if (hid == 0) {
                history = new History();
                history.setGoodsId(id);
                history.setUserId(userId);
                history.setBrowseTime(new Date());
                history.setTimes(1);
            } else {
                history = historyService.load(hid);
                history.setTimes(history.getTimes() + 1);
            }
            historyService.add(history);
        }
        Goods goods = goodsService.load(id);
        model.addAttribute("goods", goods);
        List<String> fourImageList=new ArrayList<String>();
        String fourImageStr=goods.getFourImage();
        if(fourImageStr!=null) {
            Collections.addAll(fourImageList, fourImageStr.split(";"));
        }
        List<String> detailImageList=new ArrayList<String>();
        String detailImageStr=goods.getDetailImage();
        if(detailImageStr!=null){
            Collections.addAll(detailImageList, detailImageStr.split(";"));
        }
        model.addAttribute("fourImageList", fourImageList);
        model.addAttribute("detailImageList", detailImageList);

        List<Goods> goodsList = goodsService.findRecommendGoods(id, "equalPrice");
        model.addAttribute("equalPrice", goodsList);
        List<Goods> goodsList1 = goodsService.findRecommendGoods(id, "equalBrand");
        model.addAttribute("equalBrand", goodsList1);

        return "goodsDetail";
    }

    /**
     * 评论页面
     * @param request
     * @return
     */
    @RequestMapping(value = "/{id}/comment", method = RequestMethod.GET)
    public String comment(@PathVariable int id,HttpServletRequest request,Model model) {

        String status  =request.getParameter("status");
        System.out.println(status);
        this.goodsId=id;
        if(status!=null&&!"".equals(status.trim())){
            model.addAttribute("commentList",commentService.findCommentByLevel(id,status));
        }else{
            model.addAttribute("commentList",commentService.findCommentByGoods(id));
        }
        model.addAttribute("status",status);

        return "goodsComment";
    }
    @RequestMapping(value = "/addComment", method = RequestMethod.POST)
    public String addComment(@RequestParam("orderId") String orderId,@RequestParam("goodsId") String goodsId,@RequestParam("review") String review,@RequestParam("content") String content,Model model,HttpSession session) {
        Comment comment=new Comment();
        System.out.println("id:"+goodsId);
        comment.setGoodsId(Integer.parseInt(goodsId));
        comment.setReview(Integer.parseInt(review));
        comment.setContent(content);
        User user = (User) session.getAttribute("loginUser");
        comment.setUser(user);
      //  comment.setUserId(user.getId());
        comment.setCommentTime(new Date());
        commentService.add(comment);
        reviewGoods.add(goodsId);
        System.out.println("id:"+reviewGoods);
        Order order = orderService.load(Integer.parseInt(orderId));
        Set<OrderItem> orderItems = new HashSet<OrderItem>();
        orderItems = order.getOrderItems();
        List<OrderItem> list= new ArrayList<OrderItem>();
        for(OrderItem item:orderItems){
            list.add(item);
        }
        System.out.println("p"+list.size());
        List<OrderItem> List1= new ArrayList<OrderItem>();
        int i=0;
        for(int j=0;j<reviewGoods.size();j++){
            for(int m=0;m<list.size();m++) {
                if (Integer.parseInt(reviewGoods.get(j).toString())==(list.get(m).getGoods().getId())) {
                    List1.add(i, list.get(m));
                    i++;
                }
            }
        }
        list.removeAll(List1);
        System.out.println("****"+list.size());
        if(list.size()==0) {
            orderService.updateState(Integer.parseInt(orderId), "已评论");
            throw new MartException("订单评论成功");
        }
        else {
            model.addAttribute("orderId", orderId);
            model.addAttribute("order", list);
            return "user/comment";
        }
    }
    @RequestMapping(value = "/monthSta" )

    public void  monthSta( HttpServletResponse response,HttpSession session) throws IOException {

        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html");

        double a=(double)commentService.findCommentByLevel(goodsId,"good").getTotal();
        double b=(double)commentService.findCommentByLevel(goodsId,"middle").getTotal();
        double c=(double)commentService.findCommentByLevel(goodsId,"bad").getTotal();
        double d=a+b+c;
        if(d==0){
            response.getWriter().write("该商品暂无评论！");
        }else{
            String str= "[['差评',"+c/d+"],['中评',"+b/d+"],{name: '好评',y:"+a/d+",sliced: true, selected: true}]";
            System.out.println(str);
            response.getWriter().write(str);
        }
    }

}
